#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <arpa/inet.h>
#include <event2/event.h>
#include <event2/bufferevent.h>

void read_cb(struct bufferevent* bev, void* ctx);
void event_cb(struct bufferevent* bev, short events,void* ctx);
void read_term(evutil_socket_t fd, short what, void*arg);

int main()
{
    //init server info
    struct sockaddr_in serv;
    memset(&serv,0,sizeof (serv));
    serv.sin_family = AF_INET;
    serv.sin_port = htons(8888);
    inet_pton(AF_INET, "127.0.0.1",&serv.sin_addr.s_addr);

    //创建套接字
    int fd = socket(AF_INET, SOCK_STREAM, 0);
    //创建事件处理框架
    struct event_base* base = event_base_new();

    //创建事件,设置回调函数,启动读缓冲区
    struct bufferevent* bev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE);
    bufferevent_setcb(bev, read_cb, NULL, event_cb, NULL);
    bufferevent_enable(bev, EV_READ);

    //连接服务器
    bufferevent_socket_connect(bev, (struct sockaddr*)&serv, sizeof (serv));

    //创建新事件
    struct event* ev = event_new(base, STDIN_FILENO, EV_READ | EV_PERSIST, read_term, bev);
    //添加事件到事件处理框架
    event_add(ev, NULL);

    //事件循环
    event_base_dispatch(base);

    //释放资源
    event_free(ev);
    event_base_free(base);
    return 0;
}

void read_term(evutil_socket_t fd, short what, void* arg)
{
    struct bufferevent* bev = (struct bufferevent*)arg;
    char buf[1024] = {0};
    ssize_t len = read(fd, buf, sizeof (buf));
    bufferevent_write(bev, buf, (size_t)len+1);
}

void read_cb(struct bufferevent* bev, void* ctx)
{
    char buf[1024] = {0};
    size_t len = bufferevent_read(bev, buf, sizeof (buf));
    printf("rece data: %s\n", buf);

    //bufferevent_write(bev, buf, len+1);
}

void event_cb(struct bufferevent* bev, short events,void* ctx)
{
    if (events & BEV_EVENT_EOF)
    {
        printf("connection closed...\n");
    }
    else if (events & BEV_EVENT_ERROR)
    {
        printf("some other error\n");
    }
    else if (events & BEV_EVENT_CONNECTED)
    {
        printf("connect\n");
        return;
    }

    //释放bufferevent资源
    bufferevent_free(bev);
}



